<?php


namespace app\admin\controller\admin;

use app\common\controller\Backstage;
use thans\jwt\facade\JWTAuth;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("管理员相关")
 */
class Admin extends Backstage
{

    //中间件不验证的方法
    protected $middleware = [
        'app\\middleware\\Admin' => [
            'except' => ['info']
        ]
    ];

    /**
     * @Apidoc\Title("管理员列表")
     * @Apidoc\Url("/admin/admin.Admin/listApi")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("keyword", type="string", desc="关键字")
     * @Apidoc\Param("keyword_time", type="array", desc="数组0开始 1结束")
     * @Apidoc\Param("page", type="int", desc="第几页默认第1页")
     * @Apidoc\Param("page_size", type="int", desc="每页几条默认10条")
     * @Apidoc\Returned("data", type="array", desc="返回说明")
     * @Apidoc\Returned("total", type="int", desc="总条数")
     */
    public function listApi()
    {
        try {
            $param = $this->request->param();
            $page_size = empty($param['page_size']) ? 10 : $param['page_size'];
            //条件
            $where = [];
            $where[] = ['a.delete_time', '=', 0];
            //模糊查询
            if (!empty($param['keyword'])) {
                $where[] = ['a.remark|ar.role_name|a.name|a.phone', 'like', "%{$param['keyword']}%"];
            }
            //时间查询
            if (!empty($param['keyword_time'])) {
                $time = 'a.create_time';//查询时间字段
                $timeWhere = timeWhere($param['keyword_time'][0], $param['keyword_time'][1]);
                $where[] = [$time, '>=', $timeWhere[0]];
                $where[] = [$time, '<=', $timeWhere[1] + 86399];
            }
            //排序
            $order = ['a.id' => 'DESC'];
            if (!empty($param['order']) && !empty($param['order_name'])) {
                $order_name = "a." . $param['order_name'];
                switch ($param['order']) {
                    case 1:
                        $order = [$order_name => 'DESC'];
                        break;
                    case 2:
                        $order = [$order_name => 'ASC'];
                        break;
                    default:
                        $order = ['a.id' => 'DESC'];
                }
            }
            $list_ = (new \app\common\model\Admin())
                ->alias("a")
                ->join("admin_role ar", " ar.id = a.role_id", 'left')
                ->where($where)
                ->field([
                    'a.*',
                    'ar.role_name',
                ])
                ->order($order);
            $list_ = $list_->paginate($page_size)
                ->toArray();
            $list = $list_ ['data'];
            if (!empty($list)) {
                foreach ($list as $k => $v) {
                    unset($list[$k]['delete_time']);
                    unset($list[$k]['password']);
                    $list[$k]['avatar'] = get_file_url($v['avatar']);
                    $list[$k]['lately_time'] = date("Y-m-d H:s", $v['lately_time']);
                }
            }
        } catch (\Exception $e) {
            // 这是进行异常捕获
            return $this->ajax(0, '错误' . $e->getMessage());
        }

        return $this->ajax(1, '成功', [
            'list' => $list,
            'total' => $list_['total'],
            'page_size' => $page_size
        ]);
    }

    /**
     * @Apidoc\Title("详情")
     * @Apidoc\Url("/admin/admin.Admin/info")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int",require=true, desc="列表id" )
     * @Apidoc\Returned("data", type="array", desc="返回说明")
     */
    public function info()
    {
        $post = $this->request->param();
        try {
            $this->Validate($post, [
                'id|系统错误' => 'require'
            ]);
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getError());
        }
        $info = (new \app\common\model\Admin())
            ->where(['id' => $post['id']])
            ->withoutField(['create_time', 'update_time', 'password'])
            ->find()
            ->toArray();
        //默认单图
        $info['avatar_show'] = get_file_url($info['avatar']);
        $info['role_id'] = (int) $info['role_id'];

        return $this->ajax(1, '获取成功', $info);
    }

    /**
     * @Apidoc\Title("添加修改")
     * @Apidoc\Url("/admin/admin.Admin/edit")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", desc="修改带上" )
     * @Apidoc\Param("phone", type="string", desc="手机号" )
     * @Apidoc\Param("name", type="string",require=true, desc="管理员名称" )
     * @Apidoc\Param("account", type="string",require=true, desc="账号" )
     * @Apidoc\Param("password", type="string",require=true, desc="密码添加时必填，修改不填" )
     * @Apidoc\Param("status", type="string",require=true, desc="状态：1=正常，2=冻结" )
     * @Apidoc\Param("role_id", type="int",require=true, desc="角色id" )
     * @Apidoc\Returned("data", type="array", desc="返回说明")
     */
    public function edit()
    {
        $post = $this->request->param();
        try {
            $result = JWTAuth::auth();//token验证
            $admin_id = $result['admin_id'];
            $this->Validate($post, [
                'name|管理员名称' => 'require',
                'account|账号' => 'require|length:6,20',
                'status|状态' => 'require',
                'role_id|角色' => 'require',
            ]);
            //修改
            if (isset($post['id'])) {
                if (empty($post['password'])) {
                    unset($post['password']);
                }
                $info = (new \app\common\model\Admin())
                    ->where([
                        ['account', '=', $post['account']],
                        ['delete_time', '=', 0],
                        ['id', '<>', $post['id']],
                    ])
                    ->value('id');//Exception
                if (!empty($info)) throw new \think\Exception('账号已存在');

                (new \app\common\model\Admin())
                    ->update($post);
            } else {//新增
                $info = (new \app\common\model\Admin())
                    ->where([
                        'account' => $post['account'],
                        'delete_time' => 0,
                    ])
                    ->value('id');//Exception
                if (!empty($info)) throw new \think\Exception('账号已存在');
                if (empty($post['password'])) throw new \think\Exception('密码空');
                $post['create_id'] = $admin_id;
                $post['password'] = md5(md5($post['password']) . "admin");
                (new \app\common\model\Admin())
                    ->save($post);
            }
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '成功');
    }


    /**
     * @Apidoc\Title("删除")
     * @Apidoc\Url("/admin/admin.Admin/del")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int",require=true, desc="修改带上" )
     * @Apidoc\Returned("data", type="array", desc="返回说明")
     */
    public function del()
    {
        $post = $this->request->param();
        try {
            $this->Validate($post, [
                'id|系统错误' => 'require|number',
            ]);
            //删除
            $post['delete_time'] = time();
            (new \app\common\model\Admin())
                ->update($post);
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, '成功');
    }
}
